import React, { useState, useMemo, useRef, useEffect } from 'react';

// 随机生成数据
const generateData = (num) => {
  return Array.from({ length: num }, (_, index) => ({
    id: index,
    value: Math.floor(Math.random() * 1000), 
  }));
};

const VirtualList = () => {
  const [data] = useState(generateData(100)); 
  const [scrollTop, setScrollTop] = useState(0);
  const itemHeight = 30; 
  const visibleCount = 101;
  const containerRef = useRef(null);

  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = Math.min(startIndex + visibleCount, data.length);


  const displayedData = useMemo(() => {
    return data.slice(startIndex, endIndex);
  }, [data, startIndex, endIndex]);

  useEffect(() => {
    const handleScroll = () => {
      if (containerRef.current) {
        setScrollTop(containerRef.current.scrollTop);
      }
    };

    const currentContainer = containerRef.current;
    currentContainer.addEventListener('scroll', handleScroll);

    return () => {
      currentContainer.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div
      ref={containerRef}
      style={{
        height: `${visibleCount * itemHeight}px`,
        overflowY: 'auto',
        border: '1px solid #ccc',
      }}
    >
      <div style={{ height: `${data.length * itemHeight}px`, position: 'relative' }}>
        {displayedData.map(item => (
          <div key={item.id} style={{
            height: `${itemHeight}px`,
            display: 'flex',
            alignItems: 'center',
            borderBottom: '1px solid #eee',
            paddingLeft: '10px',
          }}>
            Item {item.id}: {item.value}
          </div>
        ))}
      </div>
    </div>
  );
};

export default VirtualList;